﻿using System;
using Castle.MonoRail.Framework;
using Hadlow.Jobvertizer.Models;
using Hadlow.Jobvertizer.Repositories;
using System.Security.Permissions;

namespace Hadlow.Jobvertizer.Controllers
{
    [Scaffolding(typeof(Poster))]
    public class PosterController : BaseController
    {
        readonly IPosterRepository posterRepository;
        readonly IRepository<CreditCard> creditCardRepository;
        readonly IRepository<CardType> cardTypeRepository;

        public PosterController(
            IPosterRepository posterRepository, 
            IRepository<CreditCard> creditCardRepository,
            IRepository<CardType> cardTypeRepository)
        {
            this.posterRepository = posterRepository;
            this.creditCardRepository = creditCardRepository;
            this.cardTypeRepository = cardTypeRepository;
        }

        public void Edit(int id)
        {
            Poster poster = posterRepository.GetById(id);
            PropertyBag["poster"] = poster;

            AddCardTypesToPropertyBag();
        }

        public void Update(
            [DataBind("poster")]Poster poster)
        {
            Poster posterToUpdate = posterRepository.GetById(poster.Id);

            posterToUpdate.Name = poster.Name;
            posterToUpdate.ContactName = poster.ContactName;

            creditCardRepository.Save(poster.CreditCard);
            posterRepository.Save(posterToUpdate);

            PropertyBag["poster"] = posterToUpdate;
            RenderView("edit");

            AddCardTypesToPropertyBag();
        }

        private void AddCardTypesToPropertyBag()
        {
            CardType[] cardTypes = cardTypeRepository.GetAll();
            PropertyBag["cardTypes"] = cardTypes;
        }
    }
}
